package com.cn.algorithm.leetcode.link;

/*
*
* 链表是否有环
*
* */

import java.util.Objects;

public class HasCircle {

    public static boolean hasCircle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (Objects.equals(slow, fast)) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        ListNode head1 = new ListNode(1);
        ListNode head2 = new ListNode(2);
        head1.next = head2;
        ListNode head3 = new ListNode(3);
        head2.next = head3;
        head3.next = head1;
        System.out.println(hasCircle(head1));
        StringBuilder sb = new StringBuilder();
        sb.append("1");
    }

    public static class ListNode {
        int var;
        ListNode next;
        public ListNode(int var) {
            this.var = var;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "var=" + var +
                    ", next=" + next +
                    '}';
        }
    }
}
